"""
chat 客户端
"""
from socket import *
from multiprocessing import Process

# 服务器地址
ADDR = ("127.0.0.1", 8888)


def do_login(sock):
    while True:
        name = input("请输入昵称:")
        if len(name)<3 or " "in name:
            print("名字必须大于3且不包含空格")
            continue
        elif "管理"in name:
            print("非法名称")
            continue
        msg = "LOGIN " + name  # 请求
        sock.sendto(msg.encode(), ADDR)
        result, addr = sock.recvfrom(1024)
        if result == b'OK':
            print("进入聊天室成功")
            return name
        else:
            print("该昵称已存在")


def send_info(sock, name):
    while True:
        content = input("发送：")
        if content=="#exit#" or not content:
            return
        msg = f"CHAT {name} {content}"
        sock.sendto(msg.encode(), ADDR)


def rece_info(sock):
    while True:
        data, addr = sock.recvfrom(1024 * 1024)  # 【name-content】
        data = data.decode().split(" ", 1)
        name = data[0]
        content = data[1]
        print(f"\n{name}:{content}\n发言:",end="")


def do_exit(sock,p,name):
    msg="EXIT "+name
    sock.sendto(msg.encode(),ADDR)
    p.close()
    sock.close()
    print("您已经退出聊天室")


# 入口函数
def main():
    sock = socket(AF_INET, SOCK_DGRAM)  # UDP
    sock.bind(("0.0.0.0",56565))
    # 顺次向下按照步骤执行
    name = do_login(sock)
    p = Process(target=rece_info,args=(sock,),daemon=True)
    p.start()
    try:
        send_info(sock,name)
    except:
        pass
    do_exit(sock,p,name)


if __name__ == '__main__':
    main()
